const express = require('express');
const router = express.Router();
const mongdb = require('mongodb')
const MongoClient = require('mongodb').MongoClient;
const config = require('../config/db')
const bcrypt = require('bcryptjs');
const formidable = require('formidable');
const path = require('path')
var passport = require('passport') 
const jwt = require('jsonwebtoken')

//登录验证
router.post('/login', async function (req, res, next) {
  let { userName, userPwd } = req.body                       //获取登录用户的用户名和密码
  let client = await MongoClient.connect(config.url)      //获取数据库连接对象
  let db = client.db()
  let users = await db.collection('users').find({ 'name': userName }).toArray()    //获取和登录用户名相同的用户数据
  //判断是否存在匹配，并且密码验证正确的用户数据
  console.log('sdasds',users)
  console.log('asds',userPwd)
  if (users.length > 0 && bcrypt.compareSync(userPwd, users[0].password)) {
    jwt.sign(users[0],'mykey',{expiresIn:60*60},(err,token) => {
      if(err){
        res.json({ code: 200, message: 'error'  + err.message});
      }else{
        res.json({ code: 200, message: 'ok', user:'Bearer ' + token ,data: users[0]});
      }
    })
  } else {
    res.json({ code: 200, message: 'error' });
  }
});

//注册验证
router.post('/register', async function(req, res, next) {
  let{ userName ,userPwd} = req.body   //获取注册用户的用户名和密码
  let client = await MongoClient.connect(config.url)  //获取数据库连接对象
  let db = client.db()
  let salt = bcrypt.genSaltSync(10);   //加盐
  let hash = bcrypt.hashSync(userPwd,salt);    //加密
//创建新用户对象
 let registerUser ={
  "name":userName,
  "password":hash,
  "sex":true,
  "headpic":"default.jpg",
  "mobile":"",
  "address":null,
  "email":null,
  "birth":"null"
 }
let results = await db.collection('users').insertOne(registerUser)//执行添加用户的操作
console.log('results:',results)
//判断用户是否添加成功
if(results.acknowledged ){
  res.json({ code: 200, message: 'ok'});
}else{
  res.json({ code: 200 ,message: 'error'});
}
})

//获取当前登录用户基本信息
router.get('/getUserInfo',passport.authenticate('jwt',{session:false}), async function (req, res, next) {
  let client = await MongoClient.connect(config.url) 
  let db = client.db()
  let users = await db.collection('users').find({ }).toArray()//获取和登陆用户名相同的用户名
  console.log('users',users);
  if(users.length > 0){
    res.json({ code: 200,message:'ok',data: users})
  }else{
    res.json({ code: 200,message:'error'})
  }
});

//修改密码

router.post('/changePwd', async function (req, res, next) {
  let { userId, userOldPwd, userNewPwd } = req.body      // 获取当前用户的id和新旧密码
  let client = await MongoClient.connect(config.url)      //获取数据库连接对象
  let db = client.db()
  users = await db.collection('users').find({ '_id': new mongdb.ObjectId(userId) }).toArray() //获取和当前用户id相同的用户数据
  //判断当前用户的密码和输入原密码是否相同
  if (bcrypt.compareSync(userOldPwd, users[0].password)) {
    let salt = bcrypt.genSaltSync(10);                      //加盐
    let hash = bcrypt.hashSync(userNewPwd, salt);            //把新密码加密
    //更新旧密码
    let results = await db.collection('users').updateOne({ '_id': new mongdb.ObjectId(userId) }, { $set: { password: hash } })
    res.json({ code: 200, message: 'ok' });
  } else {
    res.json({ code: 200, message: '旧密码不正确！' });
  }

});
//上传头像
router.post('/uploadHeadPic', function(req, res, next) {
  var dirPath = path.join(__dirname,'..','public','upload')
  const form = formidable({multiples:true,uploadDir:dirPath,keepExtensions:true});
  form.parse(req,async function(err,fidlds,files){
    if(err){
      res.join({code:200,message:'上传失败'})
      return;
    }
    let headpic = files.file.newFilename
    // let userId = fields['userId']
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    await db.collection('users').updataOne({'_id':new mongdb.ObjectId(userId)},{ $set:{headpic}})
    res.json({ code: 200,message:'ok',data:headpic}) 
  })
  res.send('respond with a resource');
});

module.exports = router;
